//
//  UEServerInterface.m
//  UEHtml-iOS
//
//  Created by Qun He on 13-9-24.
//  Copyright (c) 2013年 Qun He. All rights reserved.
//

#import "UEServerInterface.h"
#import "AppDelegate.h"
#import "config.h"

@interface UEServerInterface (PrivateMethod)

-(void)httpRequestViaPOST:(NSMutableDictionary*)params apiUrl:(NSString*)apiUrl;
-(void)httpRequestViaGET:(NSMutableDictionary*)params apiUrl:(NSString*)apiUrl;
-(void)requestHasSucceeded:(MKNetworkOperation *)operation;
//-(void)requestHasFailed:(MKNetworkOperation *)operation;
@end

@implementation UEServerInterface

@synthesize redirectMethod,
hasError,
delegate,
statusCode,
errorMessage,
errorDetail,
dict;


-(id)initWithDelegate:(id)owner responseMethod:(SEL)action
{
    self = [super init];
    if(self != nil)
    {
        self.redirectMethod = action;
        self.hasError = NO;
        self.delegate = owner;
		self.statusCode = 0;
//        self.dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        engine = [[MKNetworkEngine alloc] initWithHostName:UEHTML_SERVER_API_BASE_URL customHeaderFields:nil];
    }
    return self;
}

-(void)cancelRequest
{
    [engine cancelAllOperations];
}

-(void)httpRequestViaGET:(NSMutableDictionary*)params apiUrl:(NSString*)apiUrl
{
    MKNetworkOperation *op = [engine operationWithPath:@"/index" params:nil httpMethod:@"GET" ssl:NO];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        self.hasError = NO;
        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        self.hasError = YES;
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
    }];
    [engine enqueueOperation:op];
}

-(void)httpRequestViaPOST:(NSMutableDictionary*)params apiUrl:(NSString*)apiUrl
{
    MKNetworkOperation *op = [engine operationWithPath:apiUrl params:params httpMethod:@"POST"];
    
    __block NSDictionary *responseJSON;
    __block NSError *error = nil;
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
        responseJSON=[NSJSONSerialization JSONObjectWithData:[operation responseData] options:kNilOptions error:&error];
        self.hasError = NO;
        [self requestHasSucceeded:operation];
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        self.hasError = YES;
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
    }];
    [engine enqueueOperation:op];
}

-(void)requestHasSucceeded:(MKNetworkOperation *)operation
{
    self.statusCode = operation.HTTPStatusCode;
    
    NSError *error = nil;
    self.dict = [NSJSONSerialization JSONObjectWithData:[operation responseData] options:kNilOptions error:&error];
    if (self.delegate &&[self.delegate respondsToSelector:self.redirectMethod]) {
        [self.delegate performSelector:redirectMethod withObject:self withObject:nil];
    }
   /* if(self.statusCode == 200)
    {
        NSObject *obj = nil;
        
        if (IOS_SYSTEM_VERSION >= 5.0){
            
            NSError *err = nil;
            obj = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:&err];
            if (obj!=nil&&err==nil) {
                
                NSLog(@"Successfully deserialized");
                NSLog(@"SchoolServer_obj: %@",obj);
            }
        }
       
        
        if ([obj isKindOfClass:[NSDictionary class]]) {
            
            [dict removeAllObjects];
            [dict setDictionary:(NSDictionary*)obj];
            FSLOG(@"weibo_dict: %@",dict);
            
            //		[self processError:dict];
        }
        else if ([obj isKindOfClass:[NSArray class]]) {
            
            [arr removeAllObjects];
            [arr addObjectsFromArray:(NSArray *)obj];
            FSLOG(@"weibo_arr: %@",arr);
        }
        
        if (delegate&&[delegate respondsToSelector:action]) {
            [delegate performSelector:action withObject:self withObject:nil];
        }
    }
    else
    {
        hasError = true;
        self.errorMessage = @"Server responded with an error";
        self.errorDetail  = [NSHTTPURLResponse localizedStringForStatusCode:statusCode];
        if (self.delegate &&[self.delegate respondsToSelector:self.redirectMethod]) {
            [self.delegate performSelector:self.redirectMethod withObject:self withObject:nil];
        }
        FSLOG(@"Response error, statusCode = %d", statusCode);
        return;

    }*/
}

#define serverHost               @"192.168.1.84:5558"
- (NSDictionary *)getDataFromURL:(NSString *)Path params:(NSDictionary *)data
{
    NSLog(@"MKNetwork request URL:  %@%@   \n Data: %@",serverHost,Path,data);
    
    __block NSDictionary *responseJSON;
    __block NSError *error = nil;
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:serverHost customHeaderFields:nil];
    MKNetworkOperation *op = [engine operationWithPath:Path  params:data httpMethod:@"POST" ssl:YES];
    //    在请求中添加证书
    op.clientCertificate = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"client.p12"];
    op.clientCertificatePassword = @"test";
    //   当服务器端证书不合法时是否继续访问
    op.shouldContinueWithInvalidCertificate=YES;
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
        responseJSON=[NSJSONSerialization JSONObjectWithData:[operation responseData] options:kNilOptions error:&error];
        if(error) {
            NSLog(@"JSONSerialization failed! - error: %@", error);
        };
        error=nil;
    } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        error=err;
    }];
    [engine enqueueOperation:op];
    while(!error&&!responseJSON){}
    if (error) {
        NSLog(@"MKNetwork request error : %@", error);
        return nil;
    }
    if(responseJSON){
        NSLog(@"JSONSerialization successed! - responseJSON: %@", responseJSON);
    }
    return responseJSON;
}


//-----Server interfaces--------//
//----From UEHtml Server_Interface----[2013.9.23 by Hequn]------<Begin>--//
-(void)ueHtml_getCaseList:(NSString*)rec cid:(NSString*)cid limit:(NSString*)limit firstid:(NSString*)firstid
{
    NSMutableDictionary* params=[[NSMutableDictionary alloc] initWithCapacity:0];
    [params setObject:rec forKey:@"rec"];
    [params setObject:cid forKey:@"cid"];
    [params setObject:limit forKey:@"limit"];
    [params setObject:firstid forKey:@"firstid"];
    [params setObject:@"iOS" forKey:@"ueapp"];
    
    [self httpRequestViaPOST:params apiUrl:@"service/getCaseList"];
}

-(void)ueHtml_getCaseByID:(NSString*)caseId
{
    NSMutableDictionary* params=[[NSMutableDictionary alloc] initWithCapacity:0];
    [params setObject:caseId forKey:@"id"];
    [params setObject:@"iOS" forKey:@"ueapp"];
    
    [self httpRequestViaPOST:params apiUrl:@"service/getCaseByID"];
}

@end


/*
 
 https方式：
 #define serverHost               @"192.168.1.84:5558"
 
 - (NSDictionary *)getDataFromURL:(NSString *)Path params:(NSDictionary *)data
 {
 NSLog(@"MKNetwork request URL:  %@%@   \n Data: %@",serverHost,Path,data);
 
 __block NSDictionary *responseJSON;
 __block NSError *error = nil;
 MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:serverHost customHeaderFields:nil];
 MKNetworkOperation *op = [engine operationWithPath:Path  params:data httpMethod:@"POST" ssl:YES];
 //    在请求中添加证书
 op.clientCertificate = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"client.p12"];
 op.clientCertificatePassword = @"test";
 //   当服务器端证书不合法时是否继续访问
 op.shouldContinueWithInvalidCertificate=YES;
 [op addCompletionHandler:^(MKNetworkOperation *operation) {
 NSLog(@"[operation responseData]-->>%@", [operation responseString]);
 responseJSON=[NSJSONSerialization JSONObjectWithData:[operation responseData] options:kNilOptions error:&error];
 if(error) {
 NSLog(@"JSONSerialization failed! - error: %@", error);
 };
 error=nil;
 } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
 error=err;
 }];
 [engine enqueueOperation:op];
 while(!error&&!responseJSON){}
 if (error) {
 NSLog(@"MKNetwork request error : %@", error);
 return nil;
 }
 if(responseJSON){
 NSLog(@"JSONSerialization successed! - responseJSON: %@", responseJSON);
 }
 return responseJSON;
 }
 
 
 NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:@"admin",@"userName", @"123",@"password", nil];
 NSDictionary *responseDict = [self getDataFromURL:@"/login" params:params];
 
 下载文件：
 +(MKNetworkOperation*) downloadFatAssFileFrom:(NSString*) remoteURL toFile:(NSString*) filePath {
 MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"127.0.0.1:5558" customHeaderFields:nil];
 MKNetworkOperation *op = [engine operationWithURLString:remoteURL
 params:nil
 httpMethod:@"GET"];
 
 [op addDownloadStream:[NSOutputStream outputStreamToFileAtPath:filePath
 append:YES]];
 [engine enqueueOperation:op];
 return op;
 }
 +(void)testDownload{
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
 NSString *cachesDirectory = [paths objectAtIndex:0];
 NSString *downloadPath = [cachesDirectory stringByAppendingPathComponent:@"DownloadedFile.pdf"];
 
 MKNetworkOperation *downloadOperation=[HttpManager downloadFatAssFileFrom:@"http://127.0.0.1:5558/QQ"
 toFile:downloadPath];
 
 [downloadOperation onDownloadProgressChanged:^(double progress) {
 //下载进度
 NSLog(@"download progress: %.2f", progress*100.0);
 }];
 //事件处理
 [downloadOperation addCompletionHandler:^(MKNetworkOperation* completedRequest) {
 NSLog(@"download file finished!");
 }  errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
 NSLog(@"download file error: %@", err);
 }];
 }
 上传文件：
 +(MKNetworkOperation*) uploadImageFromFile:(NSString*) filePath mimeType:(NSString *)fileType{
 MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"127.0.0.1:5558" customHeaderFields:nil];
 MKNetworkOperation *op = [engine operationWithPath:@"upload"
 params:[NSDictionary dictionaryWithObjectsAndKeys:
 @"admin", @"username",
 @"123", @"password",nil]
 httpMethod:@"POST"];
 
 [op addFile:filePath forKey:@"media" mimeType:fileType];
 
 // setFreezable uploads your images after connection is restored!
 [op setFreezable:YES];
 
 [op addCompletionHandler:^(MKNetworkOperation* completedOperation) {
 
 NSString *responseString = [completedOperation responseString];
 NSLog(@"server response: %@",responseString);
 } errorHandler:^(MKNetworkOperation *errorOp, NSError* err){
 
 NSLog(@"Upload file error: %@", err);
 }];
 
 [engine enqueueOperation:op];
 
 return op;
 }
 
 +(void)testUpload{
 NSString *uploadPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SampleImage.jpg"];
 //    NSData *myData = [NSData dataWithContentsOfFile:uploadPath];
 //    NSLog(@">>>>>>>>%@",myData);
 MKNetworkOperation *uploadOperation = [HttpManager uploadImageFromFile:uploadPath mimeType:@"jpg"];
 [uploadOperation onUploadProgressChanged:^(double progress) {
 //        上传进度
 DLog(@"Upload file progress: %.2f", progress*100.0);
 }];
 }
 */